package cn.chitanda.weather.ui.Weather


import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.viewpager2.widget.ViewPager2
import cn.chitanda.weather.R
import com.google.android.material.appbar.AppBarLayout
import com.jaeger.library.StatusBarUtil
import kotlinx.android.synthetic.main.fragment_weather.*
import kotlinx.coroutines.launch

/**
 * A simple [Fragment] subclass.
 */
class WeatherFragment : Fragment() {
    private val weatherViewModel by lazy {
        ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory(requireActivity().application)
        ).get(WeatherViewModel::class.java)
    }
    private val viewPagerAdapter by lazy { ViewPagerAdapter() }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_weather, container, false)

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        StatusBarUtil.setDarkMode(requireActivity())
        weather_TB.setExpandedTitleColor(Color.WHITE)
        weather_TB.setCollapsedTitleTextColor(Color.WHITE)
        viewPager2.adapter = viewPagerAdapter
        viewPager2.isNestedScrollingEnabled = false
        if (ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 1)
        } else {
            loadData()
        }
        toCityListActionButton.setOnClickListener {
            findNavController().navigate(R.id.action_weatherFragment_to_cityListFragment)
        }

        appBar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
            override fun onOffsetChanged(p0: AppBarLayout?, p1: Int) {
                if (!swiperefresh.isRefreshing) {
                    swiperefresh.isEnabled = (nestedScrollView.scrollY == p1)
                }
            }
        })

        swiperefresh.setProgressViewOffset(false, 100, 700)
        swiperefresh.setOnRefreshListener {
            lifecycleScope.launch { weatherViewModel.getWeatherList() }
            viewPagerAdapter.notifyItemChanged(viewPager2.currentItem)
        }
    }

    private fun loadData() {
        weatherViewModel.cityList.observe(viewLifecycleOwner, Observer {
            swiperefresh.isRefreshing = true
            lifecycleScope.launch {
                weatherViewModel.getWeatherList(it)
            }
        })

        weatherViewModel.weatherList.observe(viewLifecycleOwner, Observer {
            swiperefresh.isRefreshing = false
            viewPagerAdapter.submitList(it)
        })

        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                if (weatherViewModel.weatherList.value != null) weather_TB.title =
                    weatherViewModel.weatherList.value!![position].basic.location
            }
        })

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    loadData()
                } else {
                    requireActivity().finish()
                }
            }
        }
    }

}
